/*
 * Utility.cpp
 *
 *  Created on: 2018年1月8日
 *      Author: terry
 */

#include "Utility.h"
#include "Socket.h"

#ifdef WIN32
#else
#include <sys/types.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#endif //

Utility::Utility()
{

}

Utility::~Utility()
{
}

std::string Utility::getHostIp()
{
	std::string ip = comn::SockAddr::getLocalIP();

#ifdef WIN32

#else
	if (ip.empty() || (ip == "127.0.0.1"))
	{
		struct ifaddrs * ifAddrStruct=NULL;
		void * tmpAddrPtr=NULL;

		getifaddrs(&ifAddrStruct);

		while (ifAddrStruct!=NULL) {
			if (ifAddrStruct->ifa_addr->sa_family==AF_INET) { // check it is IP4
				// is a valid IP4 Address
				tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
				char addressBuffer[INET_ADDRSTRLEN];
				inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);

				ip = addressBuffer;
				if (ip.size() && (ip != "127.0.0.1"))
				{
					break;
				}

			} else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6) { // check it is IP6
			}
			ifAddrStruct=ifAddrStruct->ifa_next;
		}
	}
#endif

	return ip;
}
